package com.hongtao3.hsync;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;

import org.json.JSONObject;

import com.hongtao3.hsync.vo.Meta;
import com.hongtao3.hsync.vo.Server;

public class Hsync extends Server {
   
   public Hsync(String host_url,String remote_doc_root,String userName,String passpord){
	   this.host_url=host_url;
	   this.remote_doc_root=remote_doc_root;
	   this.userName=userName;
	   this.password=passpord;
   }
   
   public String post(String fn,Properties postData) throws Exception{
	   String s=null;
	   Properties data=null;
	   if(postData!=null){
		   data=postData;
	   }else{
		   data=new Properties();
	   }
	   data.put("user",userName);
	   long t=new Date().getTime()/1000;
	   data.put("client_time",t+"");
	   data.put("token",SecurityUtil.MD5(password+t));
	   data.put("fn",fn);
		s=HttpUtil.httpPost(host_url, data, null, null);
	   return s;
   }
   
   public String getVersion() throws Exception{
	   return post("version", null);
   }
   
   public HashMap<String, Meta> getRootMeta() throws Exception{
	   return getMeta(remote_doc_root, false);
   }
   
   public HashMap<String, Meta> getMeta(String remotePath,boolean recursive) throws Exception{
	   Properties data=new Properties();
	   data.put("recursive", recursive?"1":"0");
	   data.put("remote", remotePath);
	   HashMap<String, Meta> metas=new HashMap<String, Meta>();
	   String meta_str=post("meta", data);
	   String[] lines=meta_str.split("\n");
	   for(String l:lines){
		   if(l.length()<1 || !l.startsWith("{"))continue;
		   Meta meta=new Meta(new JSONObject(l));
		   metas.put(meta.getPath(), meta);
	   }
	   return metas;
   }
}
